# Copyright 2022 99Cloud, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

from logging import LoggerAdapter
from typing import Any, Dict

import paho.mqtt.client as mqtt
from oslo_log import log
from sqlalchemy.orm import Session

from dandelion import crud, schemas
from dandelion.api.deps import get_redis_conn
from dandelion.db import session
from dandelion.mqtt.service import RouterHandler

LOG: LoggerAdapter = log.getLogger(__name__)


class RSUHeartbeatRouterHandler(RouterHandler):
    def handler(self, client: mqtt.MQTT_CLIENT, topic: str, data: Dict[str, Any]) -> None:
        db: Session = session.DB_SESSION_LOCAL()
        redis_conn = get_redis_conn()

        rsu_esn = data.get("rsuEsn")
        if not rsu_esn:
            LOG.warn(f"{topic} => rsu_esn is None")
            return None
        rsu = crud.rsu.get_by_rsu_esn(db, rsu_esn=rsu_esn)
        if not rsu:
            LOG.info(f"{topic} => RSU [rsu_esn: {rsu_esn}] not found")
            return None
        crud.rsu.update_online_status(
            db, db_obj=rsu, obj_in=schemas.RSUUpdateWithStatus(onlineStatus=True)
        )
        redis_conn.set(f"RSU_ONLINE_{rsu_esn}", 1, ex=15)
        LOG.info(f"{topic} => RSU [rsu_esn: {rsu_esn}] onlineStatus updated")
